import React, { Component } from "react";
import { Checkbox, Input, Button, Icon, Spin, message } from "antd";
import moment from "moment";
import { connect } from "dva";
import FixedBottomWrapper from "../../components/FixedBottomWrapper";
import styles from "./PlanDetail.less";

const { TextArea } = Input;

@connect(stores => ({
  planData: stores.addPlan
}))
class PlanDetail extends Component {
  state = { checked: ["1"], planAudit: {}, newLoading: false, advice: "" };

  componentDidMount() {
    this.setState({
      newLoading: true
    });
    setTimeout(() => {
      const { planAudit } = this.props.planData;
      this.setState({
        planAudit
      });
      const { dispatch } = this.props;
      dispatch({
        type: "addPlan/detailPlan",
        payload: { planId: planAudit.planId }
      }).then(() => {
        const { planData } = this.props;
        const { detailPlan = {} } = planData;
        if (planAudit.operate === "detail") {
          this.setState({
            checked: this.getstatus(detailPlan.auditStatus)
          });
          if (detailPlan.auditStatus === -1) {
            this.setState({
              advice: detailPlan.auditDescribe
            });
          }
        }
        this.setState({
          newLoading: false
        });
      });
    }, 500);
  }

  getstatus = auditStatus => {
    if (auditStatus === 1) {
      return ["1"];
    }
    if (auditStatus === -1) {
      return ["-1"];
    }
    return [];
  };

  checkChange = e => {
    if (e && e.length === 2) {
      this.setState({
        checked: [e[1]]
      });
    } else {
      this.setState({
        checked: e
      });
    }
  };

  pushTargetType = detailPlan => {
    if (
      detailPlan &&
      detailPlan.pushUserIds &&
      detailPlan.pushUserIds !== null &&
      detailPlan.pushUserIds !== "null" &&
      detailPlan.pushUserIds !== ""
    ) {
      return "指定推送人";
    }
    if (
      detailPlan &&
      detailPlan.pushOrgIds &&
      detailPlan.pushOrgIds !== null &&
      detailPlan.pushOrgIds !== "null" &&
      detailPlan.pushOrgIds !== ""
    ) {
      return "按组织推送";
    }
    if (detailPlan && detailPlan.pushLabelId) {
      return "按目标推送";
    }
    return "推送到渠道";
  };

  pushTarget = detailPlan => {
    if (
      detailPlan &&
      detailPlan.pushUserIds &&
      detailPlan.pushUserIds !== null &&
      detailPlan.pushUserIds !== "null" &&
      detailPlan.pushUserIds !== "" &&
      detailPlan.pushUserIds.length > 0
    ) {
      return JSON.parse(detailPlan.pushUserIds)
        .map(item => item.name)
        .join("；");
    }
    if (
      detailPlan &&
      detailPlan.pushOrgIds &&
      detailPlan.pushOrgIds !== null &&
      detailPlan.pushOrgIds !== "null" &&
      detailPlan.pushOrgIds !== "" &&
      detailPlan.pushOrgIds.length > 0
    ) {
      return JSON.parse(detailPlan.pushOrgIds)
        .map(item => item.name)
        .join("；");
    }
    if (detailPlan && detailPlan.pushLabelId) {
      return detailPlan.pushLabelId;
    }
    return detailPlan.channelName;
  };

  setFreq = detailPlan => {
    if (
      detailPlan &&
      detailPlan.cronContent &&
      detailPlan.cronContent !== "{}"
    ) {
      const tp = JSON.parse(detailPlan.cronContent);
      if (detailPlan && tp.startHour) {
        return `从${tp.startHour}:00到${tp.endHour}:00每${tp.timeIntervel}小时推送一次`;
      }
      if (detailPlan && tp.designatedHour) {
        const tmp = tp.designatedHour.split(",");
        const temp = tmp.map(item => item.concat(":00"));
        return `指定时间${temp.join("、")}推送`;
      }
      if (detailPlan && tp.designatedDay && tp.frequencyType === 2) {
        const tmp = tp.designatedDay.split(",");
        const temp = tp.designatedDayHour.split(",");
        const tps = temp.map(item => item.concat(":00"));
        return `每月指定${tmp.join("、")}日，每天${tps.join("、")}推送`;
      }
      if (detailPlan && tp.designatedDayHour && tp.frequencyType === 2) {
        const tmp = tp.designatedDayHour.split(",");
        const temp = tmp.map(item => item.concat(":00"));
        return `每天${temp.join("、")}推送`;
      }
      const tmp = tp.designatedWeek.split(",");
      const temp = tp.designatedWeekHour.split(",");
      const tps = temp.map(item => item.concat(":00"));
      return `每周${tmp.join("、")}，每天${tps.join("、")}推送`;
    }
    return "-";
  };

  adviceGet = e => {
    this.setState({
      advice: e.target.value
    });
  };

  submit = () => {
    const { planId, pendingEventId } = this.state.planAudit;
    const { checked, advice } = this.state;
    if (checked.length === 0) {
      message.error("请选择审核结果");
      return;
    }
    const { dispatch, history } = this.props;
    dispatch({
      type: "addPlan/auditPlan",
      payload: {
        pendingEventId,
        specificEventId: planId,
        eventType: "1",
        stateHandle: checked[0],
        handleDescribe: advice
      }
    }).then(() => {
      const { planData } = this.props;
      const { auditPlanErr = -1 } = planData;
      if (auditPlanErr === 0) {
        message.success("审核成功");
        // history.push("/systemManager/systemManage/backLog");
        history.goBack(-1);
      } else {
        message.error("审核失败");
      }
    });
  };

  render() {
    const { planAudit } = this.state;
    const { history, planData } = this.props;
    const { detailPlan = {} } = planData;
    const { operate = "audit" } = planAudit;
    return (
      <FixedBottomWrapper
        className={styles.root}
        footer={
          operate === "detail" ? null : (
            <div
              style={{
                display: "flex",
                justifyContent: "center"
              }}
            >
              <div>
                <Button
                  type="primary"
                  style={{ marginRight: 8, marginLeft: 20 }}
                  onClick={this.submit}
                >
                  确定
                </Button>
                <Button
                  onClick={() => {
                    // history.push("/systemManager/systemManage/backLog");
                    history.goBack(-1);
                  }}
                >
                  取消
                </Button>
              </div>
            </div>
          )
        }
      >
        <Spin spinning={this.state.newLoading}>
          <div className={styles.topInfo}>
            {operate === "detail" ? (
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span className={styles.title}>基本信息</span>
                <Icon
                  type="close"
                  style={{ color: "rgba(0,0,0,0.45)", fontSize: 16 }}
                  onClick={() => {
                    // history.push("/systemManager/systemManage/backLog");
                    history.goBack(-1);
                  }}
                />
              </div>
            ) : (
              <span className={styles.title}>基本信息</span>
            )}
            <div style={{ display: "flex" }}>
              <div style={{ width: "50%" }}>
                <div style={{ marginBottom: 16 }}>
                  计划名称：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {detailPlan.planName ? detailPlan.planName : "-"}
                  </span>
                </div>
                <div style={{ marginBottom: 16 }}>
                  管理员：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {detailPlan.owner && JSON.parse(detailPlan.owner).length > 0
                      ? JSON.parse(detailPlan.owner)[0].name
                      : "-"}
                  </span>
                </div>
                <div style={{ marginBottom: 16 }}>
                  归属部门：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {detailPlan.ownerDeptName ? detailPlan.ownerDeptName : "-"}
                  </span>
                </div>
              </div>
              <div style={{ width: "50%" }}>
                <div style={{ marginBottom: 16 }}>
                  推送场景：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {detailPlan.templateName ? detailPlan.templateName : "-"}
                  </span>
                </div>
                <div style={{ marginBottom: 16 }}>
                  推送渠道：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {detailPlan.channelName ? detailPlan.channelName : "-"}
                  </span>
                </div>
              </div>
            </div>
            <div style={{ display: "flex" }}>
              计划描述：
              <span
                style={{
                  color: "rgba(0,0,0,0.65)",
                  width: "calc(100% - 120px)",
                  display: "block"
                }}
              >
                {detailPlan.planDescription ? detailPlan.planDescription : "-"}
              </span>
            </div>
          </div>
          <div className={styles.middleInfo}>
            <span className={styles.title}>规则配置</span>
            <div style={{ display: "flex" }}>
              <div style={{ width: "50%" }}>
                <div style={{ marginBottom: 16 }}>
                  目标类型：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {this.pushTargetType(detailPlan)}
                  </span>
                </div>
                <div style={{ marginBottom: 16 }}>
                  推送目标：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {this.pushTarget(detailPlan)}
                  </span>
                </div>
                <div style={{ display: "flex" }}>
                  推送方式：
                  <span
                    style={{
                      color: "rgba(0,0,0,0.65)"
                    }}
                  >
                    {detailPlan.pushTriggerType === 0 ? "实时推送" : "定时推送"}
                  </span>
                </div>
              </div>
              <div style={{ width: "50%" }}>
                <div style={{ marginBottom: 16 }}>
                  推送频率：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {this.setFreq(detailPlan)}
                  </span>
                </div>
                <div style={{ marginBottom: 16 }}>
                  计划有效期：
                  <span style={{ color: "rgba(0,0,0,0.65)" }}>
                    {moment(detailPlan.startTime).format("YYYY-MM-DD HH:mm:ss")}{" "}
                    ~ {moment(detailPlan.endTime).format("YYYY-MM-DD HH:mm:ss")}
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div style={{ paddingTop: 16, paddingBottom: 24 }}>
            <span className={styles.title}>审批信息</span>
            <div style={{ color: "rgba(0,0,0,0.85)" }}>
              审批结果：
              <Checkbox.Group
                value={this.state.checked}
                onChange={this.checkChange}
                disabled={operate === "detail"}
              >
                <Checkbox value="1">通过</Checkbox>
                <Checkbox value="-1">不通过</Checkbox>
              </Checkbox.Group>
            </div>
            {this.state.checked.length > 0 && this.state.checked[0] === "-1" ? (
              <div className={styles.advice}>
                <div style={{ marginTop: 4, width: 70 }}>审批意见：</div>
                <TextArea
                  style={{ width: "calc(100% - 70px)", height: 56 }}
                  disabled={operate === "detail"}
                  onChange={this.adviceGet}
                  value={this.state.advice}
                  maxLength={50}
                />
              </div>
            ) : null}
          </div>
        </Spin>
      </FixedBottomWrapper>
    );
  }
}

export default PlanDetail;
